import { Form, Input, Button, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import React, { Component } from "react";
import { validatePassword } from "../../utils/validator";

export default class Login extends Component {
  // 表单布局
  formItemLayout = {
    // labelCol: { span: 6 },
    // wrapperCol: { span: 14 },
  };

  // 初始化表单数据
  initialFormData = {
    username: "",
    password: "",
  };

  // 表单实例，可用于后续表单取值赋值
  formRef = React.createRef();

  /**
   * 表单提交 校验成功
   * @param values
   */
  onFinish = (values) => {
    console.log("Success:", values);
    if (values.username === "admin1" && values.password === "123qwe") {
      message.success("登录成功");
      // 跳转路由
      this.props.history.push("/home");
    } else {
      message.error("用户名或密码错误 admin1 123qwe");
    }
  };
  /**
   * 表单提交 校验失败
   * @param values
   */
  onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  /**
   * 表单外 提交
   */
  onSubmit = async () => {
    try {
      const values = await this.formRef.current.validateFields();
      console.log("Success:", values);
      message.success("登录成功");
    } catch (errorInfo) {
      message.error("用户名或密码错误");
      console.log("Failed:", errorInfo);
    }
  };

  render() {
    return (
      <div className="login-box">
        <h3 className="login-title">登录</h3>
        <Form
          {...this.formItemLayout}
          ref={this.formRef}
          validateMessages={this.validateMessages}
          validateTrigger="onBlur"
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
        >
          {/* 用户名 */}
          <Form.Item
            name="username"
            rules={[
              { required: true, message: "用户名必填" },
              { type: "string", min: 6, message: "长度不能小于6" },
            ]}
          >
            <Input
              prefix={<UserOutlined className="login-form-item-icon" />}
              placeholder="username"
            />
          </Form.Item>
          {/* 密码 */}
          <Form.Item
            name="password"
            rules={[
              { required: true, message: "密码必填" },
              { type: "string", min: 6, max: 20, message: "长度6~20" },
              { validator: validatePassword },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="login-form-item-icon" />}
              placeholder="password"
            />
          </Form.Item>

          {/* 提交 submit */}
          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-btn">
              登录
            </Button>
          </Form.Item>
        </Form>

        {/* 表单外的提交按钮，测试获取表单数据 */}
        <Button type="primary" onClick={this.onSubmit}>
          表单外提交按钮
        </Button>
      </div>
    );
  }
}
